<template>
  <div class="address-management">
    <el-button type="success" @click="openAddDialog">新增地址</el-button>
    <el-divider />
    <el-table :data="addressList" stripe style="width: 100%">
      <el-table-column prop="id" label="序号" width="80px" />
      <el-table-column prop="receiverName" label="收货人" />
      <el-table-column prop="receiverPhone" label="联系电话" />
      <el-table-column label="收货地址">
        <template #default="scope">
          {{ scope.row.province }}{{ scope.row.city }}{{ scope.row.district
          }}{{ scope.row.detailAddress }}
        </template>
      </el-table-column>
      <el-table-column prop="postalCode" label="邮政编码" />
      <el-table-column label="默认地址">
        <template #default="scope">
          <el-tag v-if="scope.row.isDefault === 1" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteAddress(scope.row.id)"
            >删除</el-button
          >
          <el-button
            v-if="scope.row.isDefault !== 1"
            size="small"
            type="primary"
            @click="setDefaultAddress(scope.row.id)"
          >
            设为默认
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 地址编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        :model="addressForm"
        :rules="addressRules"
        ref="addressFormRef"
        label-width="100px"
      >
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="addressForm.receiverName" />
        </el-form-item>
        <el-form-item label="联系电话" prop="receiverPhone">
          <el-input v-model="addressForm.receiverPhone" />
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-input v-model="addressForm.province" />
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input v-model="addressForm.city" />
        </el-form-item>
        <el-form-item label="区/县" prop="district">
          <el-input v-model="addressForm.district" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="addressForm.detailAddress" type="textarea" />
        </el-form-item>
        <el-form-item label="邮政编码" prop="postalCode">
          <el-input v-model="addressForm.postalCode" />
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch
            v-model="addressForm.isDefault"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddress">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import instance from "@/utils/request";

// 地址列表
const addressList = ref([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const isEdit = ref(false);

// 表单引用
const addressFormRef = ref(null);

// 地址表单数据
const addressForm = ref({
  id: null,
  receiverName: "",
  receiverPhone: "",
  province: "",
  city: "",
  district: "",
  detailAddress: "",
  postalCode: "",
  isDefault: 0,
});

// 表单验证规则
const addressRules = {
  receiverName: [{ required: true, message: "请输入收货人姓名", trigger: "blur" }],
  receiverPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
  ],
  province: [{ required: true, message: "请选择省份", trigger: "change" }],
  city: [{ required: true, message: "请选择城市", trigger: "change" }],
  district: [{ required: true, message: "请选择区/县", trigger: "change" }],
  detailAddress: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  postalCode: [
    { required: true, message: "请输入邮政编码", trigger: "blur" },
    { pattern: /^\d{6}$/, message: "请输入正确的邮政编码", trigger: "blur" },
  ],
};




// 获取地址列表
const getAddressList = async () => {
  try {
    const response = await instance.get("/address/list");

    if (response.data.code === 200) {
      addressList.value = response.data.data.map((item) => ({
        ...item,
        id: item.id || Date.now() + Math.random(), // 如果没有id则临时生成一个
      }));
    } else {
      ElMessage.error(response.data.message || "获取地址列表失败");
    }
  } catch (error) {
    console.error("获取地址列表出错:", error);
    ElMessage.error("获取地址列表失败");
  }
};

// 打开新增地址对话框
const openAddDialog = () => {
  dialogTitle.value = "新增地址";
  isEdit.value = false;
  // 重置表单
  addressForm.value = {
    id: null,
    receiverName: "",
    receiverPhone: "",
    province: "",
    city: "",
    district: "",
    detailAddress: "",
    postalCode: "",
    isDefault: 0,
  };
  dialogVisible.value = true;
};

// 打开编辑地址对话框
const openEditDialog = (address) => {
  dialogTitle.value = "编辑地址";
  isEdit.value = true;
  // 填充表单数据
  addressForm.value = { ...address };
  dialogVisible.value = true;
};

// 提交地址（新增或修改）
const submitAddress = async () => {
  addressFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response;
        if (isEdit.value) {
          // 修改地址
          response = await instance.put("/address/update", addressForm.value);
        } else {
          // 新增地址
          response = await instance.post("/address/add", addressForm.value);
        }

        if (response.data.code === 200) {
          ElMessage.success(isEdit.value ? "修改地址成功" : "新增地址成功");
          dialogVisible.value = false;
          getAddressList(); // 重新获取地址列表
        } else {
          ElMessage.error(
            response.data.message || (isEdit.value ? "修改地址失败" : "新增地址失败")
          );
        }
      } catch (error) {
        console.error("操作地址出错:", error);
        ElMessage.error(isEdit.value ? "修改地址失败" : "新增地址失败");
      }
    }
  });
};

// 删除地址
const deleteAddress = (id) => {
  ElMessageBox.confirm("确定要删除这个地址吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const response = await instance.delete(`/address/delete/${id}`);

        if (response.data.code === 200) {
          ElMessage.success("删除地址成功");
          getAddressList(); // 重新获取地址列表
        } else {
          ElMessage.error(response.data.message || "删除地址失败");
        }
      } catch (error) {
        console.error("删除地址出错:", error);
        ElMessage.error("删除地址失败");
      }
    })
    .catch(() => {
      // 用户取消删除

    });
};

// 设置默认地址
const setDefaultAddress = async (id) => {
  try {
    const response = await instance.put(`/address/setDefault/${id}`);

    if (response.data.code === 200) {
      ElMessage.success("设置默认地址成功");
      getAddressList(); // 重新获取地址列表
    } else {
      ElMessage.error(response.data.message || "设置默认地址失败");
    }
  } catch (error) {
    console.error("设置默认地址出错:", error);
    ElMessage.error("设置默认地址失败");
  }
};

// 对话框关闭时的处理
const handleDialogClose = () => {
  addressFormRef.value.resetFields();
};

// 组件挂载时获取地址列表
onMounted(() => {
  getAddressList();
});
</script>

<style scoped>
.address-management {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
